package com.sql;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.mysql.jdbc.Connection;

import net.sf.json.JSONObject;

public class edit {
	public static String Edit(int id,String name,String nickname,String email,String sex,int age){
		 String s="";
			try {
				Connection con = getConnection();
				  PreparedStatement psql;

				psql = con.prepareStatement("update user set name=?,nickname=?,age=?,email=?,sex=? where id=?");
				   psql.setString(1, name);
				   psql.setString(2, nickname);
				   psql.setInt(3, age);
				   psql.setString(4, email);
				   psql.setString(5, sex);
				   psql.setInt(6, id);

				
				   psql.executeUpdate();

			s= "success";
				
				psql.close();
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println(e);
				s= "fail";
			//	flag=0;	
			}
			return s;
			//return flag;
	}
	
	
	public static  String Query(String name){
		
	
		 String s="";
		try {
			Connection con = getConnection();
			Statement sql_statement = con.createStatement();
			
			String query = "select * from user where name='"+name+"'";
			
			ResultSet result = sql_statement.executeQuery(query);

			s = resultSetToJson(result);
			
			sql_statement.close();
			con.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		//	flag=0;	
		}
		return s;
		//return flag;
		
}
public static Connection getConnection() throws SQLException, java.lang.ClassNotFoundException {

Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/emergency";
String username = "root";
String password = "liuxingyu";

Connection con = (Connection) DriverManager.getConnection(url, username, password);
return con;
}

public static String resultSetToJson(ResultSet rs) throws SQLException,JSONException  
{  
   // json数组  
   JSONArray array = new JSONArray();  
    
   // 获取列数  
   ResultSetMetaData metaData = rs.getMetaData();  
   int columnCount = metaData.getColumnCount();  
   JSONObject jsonObj = new JSONObject();  
   // 遍历ResultSet中的每条数据  
    while (rs.next()) {  
        
         
        // 遍历每一列  
        for (int i = 1; i <= columnCount; i++) {  
            String columnName =metaData.getColumnLabel(i);  
            String value = rs.getString(columnName);  
            jsonObj.put(columnName, value);  
        }   
       // array.add(jsonObj);   
    }  
    
   return jsonObj.toString();  
}  
}
